package com.zoe.vhr.config;

import cn.hutool.core.map.MapUtil;
import com.zoe.vhr.enums.MailConfigEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Map;

/**
 * @author zoe.Zhang
 * @date 2023/01/04
 * @description
 */
@Configuration
@Slf4j
public class RabbitConfig {

    @Bean
    public Queue mailQueue() {
        return QueueBuilder.durable(MailConfigEnum.MAIL_QUEUE_NAME)
                           .build();
    }


    @Bean
    public Exchange mailExchange() {
        return ExchangeBuilder.directExchange(MailConfigEnum.MAIL_EXCHANGE_NAME)
                              .durable(true)
                              .build();
    }

    @Bean
    Binding binding(Queue mailQueue, Exchange mailExchange) {
        return BindingBuilder
                .bind(mailQueue)
                .to(mailExchange)
                .with(MailConfigEnum.MAIL_ROUTING_KEY)
                .noargs();
    }

    /**
     * 基于插件的死信队列，需要使用CustomExchange
     *
     * @return
     */
    @Bean
    public CustomExchange customExchange() {
        Map<String, Object> arguments = MapUtil.newHashMap();
        arguments.put("x-delayed-type", "direct");
        return new CustomExchange(MailConfigEnum.DELAYED_EX, MailConfigEnum.DELAYED_EX_TYPE, true, false, arguments);
    }


    @Bean
    public Queue delayedQueue() {
        return QueueBuilder.durable(MailConfigEnum.DELAYED_QUE)
                           .build();
    }

    @Bean
    public Binding delayedBinding(CustomExchange customExchange,
                                  Queue delayedQueue) {
        return BindingBuilder
                .bind(delayedQueue)
                .to(customExchange)
                .with(MailConfigEnum.DELAYED_ROUTING_KEY)
                .noargs();
    }
}
